package com.lianboke.link.ad.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TimePicker;

import com.lianboke.link.ad.R;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.utils.AlarmManagerUtils;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.SharedPreferencesUtil;
import com.lianboke.link.ad.utils.ToastUtil;

import java.lang.ref.WeakReference;

import butterknife.BindView;

/**
 * 任务定时选择
 */
public class UserOrderTimeActivity extends BaseActivity {

    @BindView(R.id.timepicker_order)
    public TimePicker timepicker_order;

    @BindView(R.id.btn_time_cancle)
    public Button btn_time_cancle;

    @BindView(R.id.btn_time_setting)
    public Button btn_time_setting;

    @BindView(R.id.tv_ordet_time)
    public TextView tv_ordet_time;

    @BindView(R.id.loading_progress)
    public ProgressBar loading_progress;


    private int iCurrenthourOfDay;//每天小时
    private int iCurrentminute;//分钟

  private   MyTimeOrderHandler myTimeOrderHandler;

    @Override
    public int getContentViewId() {
        return R.layout.activity_user_order_time;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {
        setTitleBackShow(true);
        setTitleContent("任务定时");
        myTimeOrderHandler = new MyTimeOrderHandler(this);
        btn_time_cancle.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_time_setting.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                setOrderTimeParams();
            }
        });

        /**
         * 时间变更监听
         */
        timepicker_order.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener(){
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                KLog.e("time_log",String.valueOf(hourOfDay)+":----------------------:"+String.valueOf(minute));
                iCurrenthourOfDay = hourOfDay;
                iCurrentminute = minute;
            }
        });
        //获取本地缓存
        getCacheTimeParams();
    }

    @Override
    public void TitleBackFinish() {
        super.TitleBackFinish();
        overridePendingTransition(R.anim.in_from_right,R.anim.out_to_left);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(myTimeOrderHandler!=null){
            myTimeOrderHandler.removeCallbacksAndMessages(null);
        }
        myTimeOrderHandler = null;
    }

    /**
     * 获取缓存的任务定时时间
     */
    private void getCacheTimeParams(){
        iCurrenthourOfDay =  ((Integer)SharedPreferencesUtil.getData(actContext,"time_order_hourOfday",-1)).intValue();
        iCurrentminute =  ((Integer)SharedPreferencesUtil.getData(actContext,"time_order_minute",-1)).intValue();
        if(iCurrenthourOfDay==-1 || iCurrentminute==-1){
            tv_ordet_time.setText("原任务定时时间：无");
        }else if(iCurrenthourOfDay!=-1 && iCurrentminute!=-1){
            tv_ordet_time.setText("原任务定时时间："+iCurrenthourOfDay+":"+iCurrentminute);
        }
    }


    /**
     * 设置任务的定时参数
     */
    private void setOrderTimeParams(){
        try {
            showLoadingProgress();
            SharedPreferencesUtil.saveData(actContext, "time_order_hourOfday", iCurrenthourOfDay);
            SharedPreferencesUtil.saveData(actContext, "time_order_minute", iCurrentminute);
            AlarmManagerUtils.cancleAlarmParams(appContext, CommonParams.TimerParams.TIMER_ORDER_START_ACTION, CommonParams.TimerParams.TIMER_ORDER_START_REQUEST_CODE);
            myTimeOrderHandler.sendEmptyMessageDelayed(HANDLER_TIME_ORDER_WHATE_SET_ALARM_PARAM,1000);
        }catch (Exception e){
            //
        }
    }

    /**
     * 设置任务的定时操作
     */
    private void setOrderTimerAlarmParams(){
        hideLoadingProgress();
        AlarmManagerUtils.setAlarmParams(appContext, CommonParams.TimerParams.TIMER_ORDER_START_ACTION, CommonParams.TimerParams.TIMER_ORDER_START_REQUEST_CODE, iCurrenthourOfDay, iCurrentminute);
        ToastUtil.showShort(actContext,"任务定时设置成功!");
        myTimeOrderHandler.sendEmptyMessageDelayed(HANDLER_TIME_ORDER_WHATE_FINISH_PARAM,500);
    }

    /**
     * 结束
     */
    private void finishUserTimerActivity(){
        TitleBackFinish();
    }



    /**
     * 显示加载进度
     */
    private void showLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!= View.VISIBLE){
            loading_progress.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏加载进度
     */
    private void hideLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!=View.GONE){
            loading_progress.setVisibility(View.GONE);
        }
    }

    //==========================handler==============================
    public static final int HANDLER_TIME_ORDER_WHATE_SET_ALARM_PARAM = 3002;//
    public static final int HANDLER_TIME_ORDER_WHATE_FINISH_PARAM = 3003;//
   public static class MyTimeOrderHandler extends Handler {
        WeakReference<BaseActivity> mActivityReference;

       MyTimeOrderHandler(BaseActivity activity) {
            mActivityReference = new WeakReference<BaseActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            UserOrderTimeActivity mactivity = (UserOrderTimeActivity)mActivityReference.get();
           if(mactivity==null){
               return;
           }
           switch (msg.what){
               case HANDLER_TIME_ORDER_WHATE_SET_ALARM_PARAM:
                    mactivity.setOrderTimerAlarmParams();
                   break;
               case HANDLER_TIME_ORDER_WHATE_FINISH_PARAM:
                   mactivity.finishUserTimerActivity();
                   break;
           }

        }
    }
}
